import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Spin, Upload, Modal, Tooltip, message } from 'antd';
import { PrimaryC, PrimaryGhostC, NoQueryC, SecondHeaderC, InputC, FixedButtonC, AdvancedSearch, ModalC, TableC, FirstHeaderC } from '../../../comps';
import myStyle from './index.less';
const { confirm } = Modal;
import { fixedNum } from '../../../utils/utils';
import AssignDiyC from './assignDiyC';
import SettingC from './settingModalC';
import { exportFile } from '@/src/utils/commonFunc';
import ProductYield from '../SurvivalManage/common/ProductYield';
@connect(({ initialSplitM, userM: user, loading }) => ({
  initialSplitM,
  user,
  loading,
}))
@Form.create()
export default class InitialSplit extends PureComponent {
  state = {
    columnsNoAssign: undefined, //未分配
    dataSoureNoAssign: undefined,
    seriesProductId: undefined, //系列产品id（与未分配资产，产品信息 关联）
    seriesProductIdObj: {}, //选中系列产品对象
    rowData: undefined, //当前点击表格行 子产品
    modalData: undefined, //点击手动调整对应的子产品数据
    visible: false, //是否显示手动调整弹窗
    timestamp: null, //时间戳
  };
  componentDidMount() {
    this.setState(
      {
        seriesProductIdObj: this.props.seriesProductInfo || {},
        seriesProductId: this.props.seriesProductInfo?.seriesProductId,
      },
      () => {
        this.queryUnAssignAsset(); //查询未分配资产
      },
    );
  }

  //根据系列产品ID，获取未分配资产列表
  queryUnAssignAsset = () => {
    const { seriesProductId } = this.state;
    this.setState({
      columnsNoAssign: undefined, //未分配
      dataSoureNoAssign: undefined,
    }); //查询之前清除数据
    this.props.dispatch({
      type: 'initialSplitM/queryUnAssignAsset',
      payload: {
        seriesProductId: seriesProductId,
        currentPage: 1,
        numInPage: 5000,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
            item.averageMarketVal = parseFloat(item.marketValue / item.restNum); //平均市值
          });
          this.setState({
            columnsNoAssign: data.columns || [],
            dataSoureNoAssign: data.dataSource || [],
          });
        } else {
          this.setState({
            columnsNoAssign: [],
            dataSoureNoAssign: [],
          });
        }
      },
    });
  };

  //展示模态框
  showModal = (record) => {
    this.setState({
      modalData: record,
      visible: true,
    });
  };
  //未分配
  initTableNoAssign = () => {
    const { columnsNoAssign, dataSoureNoAssign } = this.state;
    columnsNoAssign &&
      columnsNoAssign.map((item) => {
        if (item.key != 'assetName' && item.key != 'restAmount') {
          item.width = parseFloat(90 / (columnsNoAssign.length - 1)) + '%';
        }
        if (item.key == 'restAmount') {
          item.width = '10%';
        }
        if (item.key == 'restAmount' || item.key == 'marketValue') {
          item.type = 'money';
        }
        if (item.key == 'assetRate' || item.key == 'weight') {
          item.type = 'rate';
          if (item.key == 'assetRate') item.toFixed = 4;
        }
        if (item.key == 'restNum') {
          item.align = 'right';
          item.render = (text) => {
            return text != null ? fixedNum(text, 2) : '--';
          };
        }
      });
    return (
      <TableC
        columns={columnsNoAssign}
        dataSource={dataSoureNoAssign}
        hidePage={true}
        scroll={dataSoureNoAssign && dataSoureNoAssign.length > 8 ? { x: '100%', y: '280px' } : {}}
        rowKey='key'
      />
    );
  };

  //智能分配
  smartAssign = () => {
    //点击智能分配，取消产品信息的选中状态，清空产品资产分配详情，全页面添加loading，提示“正在执行智能分配，请耐心等待...”；
    const { seriesProductIdObj } = this.state;
    this.setState({
      rowData: undefined,
      columnsAssigned: undefined,
      dataSoureAssigned: undefined,
    });
    this.props.dispatch({
      type: 'initialSplitM/smartAssign',
      payload: {
        seriesProductId: this.state.seriesProductId,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            message.success('智能分配成功!');
            this.queryUnAssignAsset();
            seriesProductIdObj.tag = 0; //智能分配不可点击
            this.setState({
              seriesProductIdObj,
              timestamp: new Date().getTime(),
            });
          } else {
            message.error(res.msg || '智能分配失败!');
          }
        } else {
          message.error('智能分配失败!');
        }
      },
    });
  };

  export = () => {
    //导出文件

    exportFile('api/v1/asset-split/asset-split-list-basic-info/export', {
      seriesProductId: this.state.seriesProductId,
    });
  };
  //拆分确认
  splitConfirm = () => {
    const { seriesProductIdObj } = this.state;
    confirm({
      title: '确定拆分吗?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: 'initialSplitM/splitConfirm',
          payload: {
            listId: this.state.seriesProductId,
          },
          callback: (res) => {
            if (res) {
              if (res.code == 0) {
                message.success('拆分确认成功!');
                seriesProductIdObj.confirmed = 1; //拆分按钮不可点击
                this.setState({
                  seriesProductIdObj,
                });
              } else message.error(res.msg || '拆分确认失败!');
            } else message.error('拆分确认失败!');
          },
        });
      },
    });
  };

  render() {
    const { loading } = this.props;
    const { seriesProductId, seriesProductIdObj, columnsNoAssign, dataSoureNoAssign } = this.state;
    return (
      <div className={myStyle.initialSplit}>
        <FixedButtonC
          topHtml={
            <Spin
              spinning={loading.effects['initialSplitM/smartAssign'] == true || loading.effects['initialSplitM/splitConfirm'] == true}
              tip={loading.effects['initialSplitM/splitConfirm'] == true ? '' : loading.effects['initialSplitM/smartAssign'] == true ? '正在执行智能分配，请耐心等待...' : ''}
            >
              <FirstHeaderC title={'初始拆分'} />
              <div className={myStyle.seriesName}>
                系列产品<span>{seriesProductIdObj?.listName || '--'}</span>
              </div>
              <div className={myStyle.settingC}>
                <div>
                  <span style={{ paddingRight: '5px' }}>拆分配置</span>
                  <Tooltip title={'该配置是针对单个拆分产品'}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </div>
                <SettingC id={seriesProductId} />
                <div>
                  <PrimaryC
                    title={'智能分配'}
                    helper='系统根据资产情况进行合理化分配'
                    onClick={this.smartAssign}
                    disabled={Object.keys(seriesProductIdObj).length && seriesProductIdObj.tag == 1 ? (seriesProductIdObj.confirmed == 0 ? false : true) : true}
                  />
                </div>
              </div>
              <FirstHeaderC title={'初始拆分结果'} />
              <SecondHeaderC
                title={'资产分配'}
                Right={
                  <div>
                    <PrimaryC
                      style={{ marginRight: '15px' }}
                      title={'拆分确认'}
                      helper='拆分确认后，结果不可更改，只能系列删除'
                      onClick={this.splitConfirm}
                      disabled={Object.keys(seriesProductIdObj).length && seriesProductIdObj.confirmed == 0 ? false : true}
                    />
                    <PrimaryGhostC
                      title={'数据导出'}
                      onClick={this.export}
                      disabled={seriesProductId && Object.keys(seriesProductIdObj).length && seriesProductIdObj.tag == 0 ? false : true}
                    />
                  </div>
                }
              />
              {/* { this.initTableProduct()  } */}
              <ProductYield id={seriesProductId} type={'2'} timestamp={this.state.timestamp} showModal={this.showModal} confirmed={seriesProductIdObj?.confirmed} />
              <div style={{ marginTop: '20px' }}>
                <SecondHeaderC title={'未分配资产信息'} />
              </div>
              {this.initTableNoAssign()}
            </Spin>
          }
          bottomHtml={
            <div style={{ display: 'flex', width: '100%', justifyContent: 'flex-end', height: '50px', alignItems: 'center' }}>
              <PrimaryGhostC style={{ margin: '0 10px' }} title='返回' onClick={this.props.onClose} />
            </div>
          }
        ></FixedButtonC>
        {this.state.visible && (
          <AssignDiyC
            visible={this.state.visible}
            modalData={this.state.modalData}
            triggleVisible={(e, type) => {
              if (type == 'success') {
                this.queryUnAssignAsset();
                seriesProductIdObj.tag = 0; //智能分配不可点击
                this.setState({
                  seriesProductIdObj,
                  timestamp: new Date().getTime(),
                });
              }
              this.setState({ visible: e });
            }}
            seriesProductId={seriesProductId}
            columnsNoAssign={columnsNoAssign}
            dataSoureNoAssign={dataSoureNoAssign}
          />
        )}
      </div>
    );
  }
}
